/* Copyright 2009 Palm, Inc.  All rights reserved. */



var FdneditAssistant = Class.create({

    initialize: function(target){
    
        this.entryType = 'fdn';
        
        if (!target) {
            this.phoneBookEntry = [];
            this.title = $L("Add fixed number");
            this.isEdit = false;
        }
        else {
            this.phoneBookEntry = Object.clone(target);
            this.originalEntry = target;
            this.title = $L("Edit fixed number");
            this.isEdit = true;
        }
        controller = this.controller;
    },
    
    setup: function(){
    
		this.nameInputAttributes = {
			modelProperty: 'name',
			modifierState: 'none',
			focusMode: Mojo.Widget.focusInsertMode,
			requiresEnterKey: true,
			textFieldName: "name"
		};
	
		this.controller.setupWidget('name', this.nameInputAttributes, this.phoneBookEntry);

		this.numberInputAttributes = {
			modelProperty: 'number',
			modifierState: Mojo.Widget.numLock,
			focusMode: Mojo.Widget.focusInsertMode,
			requiresEnterKey: true,
			textFieldName: "number"
			};
	
		this.controller.setupWidget('number', this.numberInputAttributes, this.phoneBookEntry);

        
		$('title').innerHTML = this.title;
        if (this.isEdit === false) { 
			$('fdnedit_delete').hide();
		}
		this.controller.listen('name', Mojo.Event.propertyChange, this.propChangeHandler.bind(this));
		this.controller.listen('number', Mojo.Event.propertyChange, this.propChangeHandler.bind(this));

        $('fdnedit_delete').observe(Mojo.Event.tap, this.handleDelete.bindAsEventListener(this));
        $('fdnedit_done').observe(Mojo.Event.tap, this.handleSave.bindAsEventListener(this));
		
		// App Menu - Remove default items and add only Edit & Help items.
		var appMenuModel = {
	        visible: true,
            items: [Mojo.Menu.editItem, {label:$L('Help'), command:Mojo.Menu.helpCmd}]
        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);
        
    },
    
    activate: function(){
        var inputElements = this.controller.sceneElement.select('input');
            inputElements[0].setAttribute("maxlength", fdn_name_length || 25);
            inputElements[1].setAttribute("maxlength", fdn_number_length || 50);
        
    },
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if (event.command == Mojo.Menu.helpCmd) {
				var r = new Mojo.Service.Request('palm://com.palm.applicationManager', {
					method: 'open',
				parameters: {'id': 'com.palm.app.help',params: {'target': 'http://help.palm.com/phone/phone_prefs/index.html'}}});
			}
		}
	},	
    
    propChangeHandler: function(event){
       
        this.phoneBookEntry[event.property] = event.value;
        this.dirty = true;
    },

	isValidDialKey: function(key){
	    for (i = 0; i < key.length; i++) {
			if (!((key[i] >= '0' && key[i] <= '9') 
				|| key[i] == '*' || key[i] == '#'
				|| key[i] == 'w' || key[i] == 'p' 
				|| key[i] == '+')) 
	            return false;
		}
	    return true;    
	},
    
    handleSave: function(event){
        $$('*:focus').each(function(element){
            element.blur();
        });
        if (this.isValidDialKey(this.phoneBookEntry.number)){
           
            this.phoneBookEntry.type = this.entryType;
            if (this.isEdit == false) {
				TelephonyService.simbookWrite(this.simbookWriteCallback.bind(this), this.phoneBookEntry.type, this.phoneBookEntry.name, this.phoneBookEntry.number);            
            }
            else {
				TelephonyService.simbookWrite(this.simbookWriteCallback.bind(this), this.phoneBookEntry.type, this.phoneBookEntry.name, this.phoneBookEntry.number,this.phoneBookEntry.index);            
            }
        }
		else{
			Mojo.Controller.errorDialog($L("Invalid number"));
		}
    },

    simbookWriteCallback: function(payload){
		
		if (payload && payload.returnValue == true) {//success
			if (payload.newIndex != undefined) 
				this.saveSuccess(payload.newIndex);
			else 
				this.saveSuccess();
		}
		else 
			if (payload && payload.returnValue == false) {
				if (Messages.serviceErrors[payload.errorCode] !== undefined) {
					payload.errorText = Messages.serviceErrors[payload.errorCode].toString();
				} else {
					payload.errorText = Messages.serviceErrors[Messages.defaultErrorIndex].toString();
				}

				Mojo.Controller.errorDialog(payload.errorText);
			}
	},
	
    saveSuccess: function(newInd){
        if (this.isEdit == false) {
            this.phoneBookEntry.index = newInd;
                      
            fdnBookList.push({
                name: this.phoneBookEntry.name,
                number: this.phoneBookEntry.number,
                index: this.phoneBookEntry.index,
                type: this.phoneBookEntry.type
            });
           
            
        }
        else {
           
            var index = fdnBookList.indexOf(this.originalEntry);
            fdnBookList[index] = this.phoneBookEntry;
            
        }
        Mojo.Controller.stageController.popScene();
        Mojo.Controller.stageController.delegateToSceneAssistant("updateListModel");
    },
    
    handleBack: function(event){
        Mojo.Controller.stageController.popScene();
    },
    
    handleDelete: function(event){
        this.entryIndex = this.phoneBookEntry.index;
        this.deleteIndex = fdnBookList.indexOf(this.originalEntry);
        
        this.dialogBox = this.controller.showDialog({
            template: 'fdnedit/dialog-delete',
            preventCancel: false,
            assistant: new DeleteConfirmAssistant(this, this.deleteEntry.bind(this))
        });
    },
    
    deleteEntry: function(){
		TelephonyService.simbookDelete(this.entryIndex, this.entryType, this.simbookDeleteCallback.bind(this));
	},
	
	simbookDeleteCallback: function(payload){
		if (payload && payload.returnValue == true) {//success
			fdnBookList.splice(this.deleteIndex, 1);
			Mojo.Controller.stageController.popScene();
		}
		else if(payload && payload.returnValue === false){//failure
			if (Messages.serviceErrors[payload.errorCode] !== undefined) {
				payload.errorText = Messages.serviceErrors[payload.errorCode].toString();
			} else {
				payload.errorText = Messages.serviceErrors[Messages.defaultErrorIndex].toString();
			}

            Mojo.Controller.errorDialog(payload.errorText);
        }
    }
    
});


var DeleteConfirmAssistant = Class.create({
    initialize: function(sceneAssistant, callback){
        this.sceneAssistant = sceneAssistant;
        this.callback = callback;
    },
    
    setup: function(widget){
        this.widget = widget;
        
        $('palm-dialog-box').focus();
        $('delete_confirm').addEventListener(Mojo.Event.tap, this.doConfirm.bindAsEventListener(this));
        $('delete_cancel').addEventListener(Mojo.Event.tap, this.doCancel.bindAsEventListener(this));
    },
    
    autonavigate: function(event, elt){
    },
    
    doConfirm: function(){
        this.widget.mojo.close();
        this.callback();
    },
    
    doCancel: function(){
        this.widget.mojo.close();
    },
    
    clearForm: function(){
    }

});


